import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import router from "./router";
import { createPinia } from "pinia";
import axios from "axios";
import { useGlobalStore } from "./store/global";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import "./assets/icons"; // 导入图标库

const app = createApp(App);
const pinia = createPinia();
app.use(router);
app.use(pinia);
// 注：初始化 useGlobalStore 必须在 app.use(pinia) 之后
const globalStore = useGlobalStore();

axios.defaults.baseURL = "http://apis.imooc.com/api";
axios.interceptors.request.use((config) => {
  globalStore.setLoading(true);
  globalStore.setError({ status: false, message: "" });

  // get 请求，添加到 url 中
  config.params = { ...config.params, icode: "0AF57F15FEC87EA3" };

  // 其他请求，添加到 body 中
  // 如果是上传文件，添加到 FormData 中
  if (config.data instanceof FormData) {
    config.data.append("icode", "0AF57F15FEC87EA3");
  } else {
    // 普通的 body 对象，添加到 data 中
    config.data = { ...config.data, icode: "0AF57F15FEC87EA3" };
  }

  return config;
});

axios.interceptors.response.use(
  (config) => {
    setTimeout(() => {
      globalStore.loading = false;
    }, 1000);

    return config;
  },
  (e) => {
    const { error } = e.response.data;
    globalStore.error = { status: true, message: error };
    globalStore.loading = false;

    return Promise.reject(e.response.data);
  }
);

app.config.errorHandler = (err, vm, info) => {
  console.error("[全局错误]", err, info);
  // 可选：发送错误到监控系统（如 Sentry）
};

// 捕获未处理的 Promise 错误
window.addEventListener("unhandledrejection", (event) => {
  console.error("[未处理的 Promise]", event.reason);
  event.preventDefault(); // 阻止默认控制台报错
});

app.component("FontAwesomeIcon", FontAwesomeIcon);
app.mount("#app");
